/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.chinalwb.are.view;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.text.RichText;
import ohos.agp.text.RichTextLayout;
import ohos.agp.utils.Rect;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

/**
 * RichTextView
 *
 * @author hal
 * @since 2021/6/23
 */
public class RichTextView extends Text implements Component.DrawTask {
    private final int width;
    private final Paint paint = new Paint();
    private RichText richText;

    public RichTextView(Context context) {
        this(context, null);
    }

    public RichTextView(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    public RichTextView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        width = DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getAttributes().width;
        paint.setMultipleLine(true);
        paint.setAntiAlias(true);
        addDrawTask(this);
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        if (richText == null) {
            return;
        }
        RichTextLayout richTextLayout = new RichTextLayout(richText, paint, new Rect(getLeft(), getTop(), width, getBottom()), width);
        richTextLayout.drawText(canvas);
    }

    /**
     * richText
     *
     * @param richText richText
     */
    public void setContent(RichText richText) {
        this.richText = richText;
        invalidate();
    }
}
